package api

import (
	"Suscan/models"
	"Suscan/pkg/e"
	"Suscan/pkg/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func AssetsSetup(c *gin.Context) {
	json := make(map[string]interface{})
	c.BindJSON(&json)
	name := fmt.Sprintf("%v", json["name"])
	assets := fmt.Sprintf("%v", json["assets"])

	code := e.SUCCESS
	assetResult := strings.Split(assets,"\n")

	for _,as := range assetResult{
		data := make(map[string]interface{})
		data["name"]=name
		data["target"]=as
		//与现有数据库中资产对比，如果存在就更新时间
		ok, id := models.ExistAsset(as,name)
		if ok {
			dataUpdate := make(map[string]interface{})
			nowTime := time.Now().Format("2006-01-02 15:04:05")
			dataUpdate["updated_time"] = nowTime
			models.EditAsset(id, dataUpdate)
		} else {
			models.AddAsset(data)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": make(map[string]string),
	})

}

func GetAssets(c *gin.Context) {
	name := c.Query("name")
	target := c.Query("target")
	create_time := c.Query("create_time")
	update_time := c.Query("update_time")

	maps := make(map[string]interface{})
	//data := make(map[string]interface{})

	if name != "" {
		maps["name"] = name
	}

	if target != "" {
		maps["target"] = target
	}

	if create_time != "" {
		maps["create_time"] = create_time
	}

	if update_time != "" {
		maps["update_time"] = update_time
	}

	code := e.SUCCESS

	pageSize, _  := strconv.Atoi(c.Query("pageSize"))

	data := models.GetAssets(utils.GetPage(c), pageSize, maps)
	total := models.GetAssetsTotal(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
		"total":total,
	})
}

type User struct {
	ID []int `json:"id"`
}

func DeleteAsset(c *gin.Context) {
	json := User{}
	c.BindJSON(&json)
	var code int
	data :=make(map[string]string)
	for _,v := range json.ID {
		a ,id := models.DeleteAsset(v)
		if a {
			code = e.SUCCESS
		}else {
			code = e.ERROR
			data["id"] = strconv.Itoa(id)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}